<template>
  <div id="inspectCompanyDiv">
    <Breadcrumb content="销售人员" />
    <div class="bodyContent">
      <Splitpanes>
        <!-- 左侧表格  -->
        <Pane size="30">
          <vxe-toolbar perfect>
            <template #buttons>
              <vxe-input style="width: 180px" v-model="searchForm.searchValue" type="search" clearable class="vxeInputSearch" placeholder="关键字查询" @clear="findSalesmanList" @keyup="keyupEnter" @search-click="findSalesmanList()"></vxe-input>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新" :loading="tloading" @click="findSalesmanList"></vxe-button>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-square-plus" content="新建" @click="addSalesman()"></vxe-button>
              <vxe-button type="text" icon="vxe-icon-delete" class="button-red" content="删除" @click="deleteSalesman"></vxe-button>
            </template>
          </vxe-toolbar>

          <div class="tableBody">
            <vxe-table ref="companyTableRef" class="mytable-scrollbar" border="inner" align="center" height="auto" :data="salesmanList" :loading="tloading" @current-change="companyRowClick" :row-config="{ isCurrent: true, isHover: true }" :column-config="{ resizable: true }" resizable show-overflow keep-source>
              <vxe-column type="checkbox" width="30"></vxe-column>
              <vxe-column field="code" title="编码">
                <template #default="{ row }">
                  <span>{{ row.code }}</span>
                </template>
              </vxe-column>
              <vxe-column field="name" title="名称">
                <template #default="{ row }">
                  <span>{{ row.name }}</span>
                </template>
              </vxe-column>
              <vxe-column field="inputCode" title="助记符">
                <template #default="{ row }">
                  <span>{{ row.inputCode }}</span>
                </template>
              </vxe-column>

              <vxe-column field="seq" title="顺序" width="50">
                <template #default="{ row }">
                  <span>{{ row.seq }}</span>
                </template>
              </vxe-column>
            </vxe-table>
            <vxe-pager align="left" min-height="32px" :current-page.sync="page.currentPage" :page-size.sync="page.pageSize" :total="page.totalResult" :layouts="[
                'PrevJump',
                'PrevPage',
                'Number',
                'NextPage',
                'NextJump',
                'Sizes',
                'FullJump',
                'Total'
              ]" @page-change="handleSizeChange($event)"></vxe-pager>
          </div>
        </Pane>
        <!-- 右侧表单 -->
        <Pane size="70">
          <el-tabs type="border-card" v-model="activeName" @tab-click="tabHandleClick">
            <el-tab-pane label="基础信息" name="first">
              <div class="divclazz">
                <el-form ref="companyFormRef" :model="companyForm" :rules="companyFormRule" label-width="100px" inline-message>
                  <el-row>
                    <el-col :span="12">
                      <el-form-item prop="code" label="编码">
                        <el-input type="text" v-model="companyForm.code" placeholder="请输入单位代码" clearable></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item prop="name" label="名称">
                        <el-input type="text" v-model="companyForm.name" placeholder="请输入单位名称	" clearable></el-input>
                      </el-form-item>
                    </el-col>

                    <el-col :span="12">
                      <el-form-item prop="inputCode" label="助记符">
                        <el-input type="text" v-model="companyForm.inputCode" placeholder="请输入助记符" clearable></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item prop="area" label="所属区域">
                        <el-cascader ref="areaCasRef" v-model="companyForm.area" style="width:300px;" filterable placeholder="请选择省-市-区" :clearable="true" :show-all-levels="true" :props="{ expandTrigger: 'click' ,value:'code',label:'name',lazy:true,lazyLoad:lazyLoadAreaList,leaf:'leaf'}"></el-cascader>
                      </el-form-item>
                    </el-col>
                    <el-col :span="24">
                      <el-form-item prop="seq" label="顺序">
                        <el-input-number v-model="companyForm.seq" :min="1" :max="1000" />
                      </el-form-item>
                    </el-col>

                    <el-col :span="24">
                      <el-form-item class="form-footer">
                        <template #default>
                          <el-button type="primary" @click="saveCompany('companyFormRef')">保存</el-button>
                        </template>
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-form>
              </div>

            </el-tab-pane>
            <el-tab-pane label="送检单位对照" name="second" :disabled="isEmpty(companyForm.id)">
              <LabInspectCompanySalesman ref="labCompanySalesmanRef" />
            </el-tab-pane>
          </el-tabs>
        </Pane>
      </Splitpanes>
    </div>
  </div>
</template>
<script setup lang="ts">
// 引入组件区 ==========
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
import Breadcrumb from '@/components/Breadcrumb.vue';
import { Splitpanes, Pane } from 'splitpanes';
let { proxy }: any = getCurrentInstance();
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage'; //提示框
import { AppStore } from '@/stores/store';
import { isEmpty } from 'lodash';
import { notifyMessage, notifyType } from '@/utils/common';
import { ElCascader } from 'element-plus'; //'../../../stores/store';
import LabInspectCompanySalesman from './LabInspectCompanySalesman.vue'; //失控记录图表

let areaCasRef = ref<InstanceType<typeof ElCascader>>();

let store = AppStore();

// 全局变量定义区 ==========
// 根据质控规则的关键字查询
let searchForm = {
  searchValue: ''
};
let tloading = ref(false); //加载状态
let activeName = ref('first');
let salesmanList: any = reactive([]);
let sltCompany: any = reactive({});
let labCompanySalesmanRef: any = ref(null);

// 条数/页
const PageSizeList = [10, 50, 100, 200, 500];
// 分页
let page = reactive({
  currentPage: 1,
  pageSize: PageSizeList[1],
  totalResult: 0
});

let companyForm = reactive({
  id: null,
  code: '',
  name: '',
  inputCode: '',
  seq: 1,
  area: []
});

let companyFormRule = {
  name: [
    {
      required: true,
      message: '请输入名称',
      trigger: 'blur'
    },
    {
      min: 2,
      max: 20,
      message: '长度为2到20个字符',
      trigger: 'blur'
    }
  ]
};
// 方法定义区 =============
// 页面加载时更新列表(左侧)
onMounted(() => {
  findSalesmanList();
});
//懒加载省市区
function lazyLoadAreaList(node: any, resolve: any) {
  if (node.isLeaf) {
    resolve();
    return;
  }
  let url = '';
  const param: any = {};
  switch (node.level) {
    case 0:
      url = '/api/common/findDictProvinceList';
      break;
    case 1:
      url = '/api/common/findDictCityList';
      param.provCode = node.value;
      break;
    case 2:
      url = '/api/common/findDictAreaList';
      param.cityCode = node.value;
      break;
  }
  proxy.$http
    .get(url, { params: param })
    .then((res: any) => {
      if (res.status.code !== 1) {
        notifyMessage(res.status.msg, notifyType.warning, proxy);
      } else {
        const nodes = res.data.dataList.map((ele: any) => {
          return {
            code: ele.code,
            name: ele.name,
            children: [],
            leaf: node.level === 2
          };
        });
        resolve(nodes);
      }
    })
    .catch((err: string) => {
      notifyMessage(err, notifyType.warning, proxy);
    });
}
function tabHandleClick(tab) {
  if (tab.props.name == 'second') {
    labCompanySalesmanRef.value.initPage(companyForm);
  }
}

function findSalesmanList() {
  tloading.value = true;
  salesmanList.length = 0; //放入数据前清空数据
  const url = '/lab/inspectSalesman/findSalesmanPageList';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: {
        seachValue: searchForm.searchValue,
        pageIndex: page.currentPage,
        pageSize: page.pageSize
      }
    })
    .then((res: any) => {
      salesmanList.push(...res.data.records);
      page.totalResult = res.data.total;
      const kn = salesmanList.find((k) => k.id == sltCompany.id);
      if (isEmpty(kn)) {
        companyRowClick({ row: salesmanList[0] }); //默认选中第一条数据
      } else {
        companyRowClick({ row: kn }); //默认选中第一条数据
      }
      tloading.value = false;
    })
    .catch((err: any) => {
      tloading.value = false;
      // VxeMessage('获取获取当前字典的规则列表失败',VxeNotifyType.error)
    });
}

// 回车查询
function keyupEnter(e: any) {
  if (e.$event.code == 'Enter') {
    findSalesmanList();
  }
}

//点击每页数量(分页查询)
function handleSizeChange({ type, currentPage, pageSize }) {
  if (type === 'size') {
    page.currentPage = 1;
  } else {
    page.currentPage = currentPage;
  }
  page.pageSize = pageSize;
  findSalesmanList();
}

// 点击设计模式表格当前行触发右侧表单变化
function companyRowClick({ row }: any) {
  if (isEmpty(row)) {
    clearDataForm();
  } else {
    (proxy.$refs.companyTableRef as any).setCurrentRow(row);
    setDataForm(row);
    if (activeName.value == 'second') {
      labCompanySalesmanRef.value.initPage(companyForm);
    }
  }
}

// 新建
function addSalesman() {
  clearDataForm();
  sltCompany = {};
  (proxy.$refs.companyTableRef as any).clearCurrentRow();
  activeName.value = 'first';
}

// 编辑当前行规则
function setDataForm(row: any) {
  companyForm.id = row.id;
  companyForm.code = row.code;
  companyForm.name = row.name;
  companyForm.inputCode = row.inputCode;
  companyForm.seq = row.seq;
  companyForm.area = [row.provinceCode, row.cityCode, row.areaCode];
  sltCompany = row;
}

// 清空中间规则弹框表单
function clearDataForm() {
  companyForm.id = null;
  companyForm.code = '';
  companyForm.name = '';
  companyForm.inputCode = '';
  companyForm.area = [];
  companyForm.seq = page.totalResult + 1;
}

function saveCompany(formName: any) {
  let $el = proxy.$refs[formName];
  $el.validate((valid: any) => {
    if (!valid) {
      return false;
    }
    if (companyForm.id === null) {
      const url = '/lab/inspectSalesman/addInspectSalesman';
      const company = {
        code: companyForm.code,
        name: companyForm.name,
        inputCode: companyForm.inputCode,
        seq: companyForm.seq,
        province: '',
        provinceCode: '',
        city: '',
        cityCode: '',
        area: '',
        areaCode: ''
      };
      //省市区
      if (companyForm.area.length === 3) {
        const areaNode: any = areaCasRef.value!.getCheckedNodes(false);
        if (areaNode.length === 1) {
          const nodes = areaNode[0].pathNodes;
          company.provinceCode = nodes[0].value;
          company.province = nodes[0].label;
          company.cityCode = nodes[1].value;
          company.city = nodes[1].label;
          company.areaCode = nodes[2].value;
          company.area = nodes[2].label;
        }
      }
      proxy.$http
        .post(url, company)
        .then((res: any) => {
          VxeMessage('新增成功', VxeNotifyType.success);
          clearDataForm();
          sltCompany.id = res.data.id;
          findSalesmanList();
        })
        .catch((err: any) => {
          VxeMessage('新增失败', VxeNotifyType.error);
        });
    } else {
      // 修改用户
      const url = '/lab/inspectSalesman/editInspectSalesman';
      const company = {
        id: companyForm.id,
        code: companyForm.code,
        name: companyForm.name,
        inputCode: companyForm.inputCode,
        seq: companyForm.seq,
        province: '',
        provinceCode: '',
        city: '',
        cityCode: '',
        area: '',
        areaCode: ''
      };
      //省市区
      if (companyForm.area.length === 3) {
        const areaNode: any = areaCasRef.value!.getCheckedNodes(false);
        if (areaNode.length === 1) {
          const nodes = areaNode[0].pathNodes;
          company.provinceCode = nodes[0].value;
          company.province = nodes[0].label;
          company.cityCode = nodes[1].value;
          company.city = nodes[1].label;
          company.areaCode = nodes[2].value;
          company.area = nodes[2].label;
        }
      }
      proxy.$http
        .post(url, company)
        .then((res: any) => {
          VxeMessage('修改成功', VxeNotifyType.success);
          sltCompany.id = res.data.id;
          setTimeout(() => {
            clearDataForm();
            findSalesmanList();
          }, 50);
        })
        .catch((err: any) => {
          VxeMessage('修改失败', VxeNotifyType.error);
        });
    }
  });
}

function deleteSalesman() {
  const sltCompanys = (proxy.$refs.companyTableRef as any).getCheckboxRecords();
  if (!(sltCompanys.length > 0)) {
    VxeMessage('请勾选要删除的数据', VxeNotifyType.info);
  } else {
    proxy
      .$confirm('确定要删除当前勾选的数据？', '提示', {
        cancelButtonClass: 'cancel-button',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(async () => {
        //后台删除数据
        const delCompanyList = sltCompanys.filter((p: any) => !isEmpty(p.id));
        if (delCompanyList.length > 0) {
          const url = '/lab/inspectSalesman/batchDeleteSalesman';
          proxy.$http
            .post(url, delCompanyList)
            .then((res: any) => {
              findSalesmanList(); // 获取检验仪器表格数据
              VxeMessage(res.status.msg, VxeNotifyType.success);
            })
            .catch((err: any) => {
              VxeMessage(err, VxeNotifyType.error);
            });
        }
      })
      .catch((err: any) => {
        // VxeMessage(err, VxeNotifyType.error);
      });
  }
}
</script>

<style lang="scss" scoped>
#inspectCompanyDiv {
  height: 100%;
  .bodyContent {
    height: calc(100% - 60px);
    .splitpanes {
      background-color: $base-white;
      // 附加按钮间距
      .button-blue,
      .button-red {
        margin: 5px 0 5px 5px;
      }
      .tableBody {
        height: calc(100% - 40px - 32px);
      }
      .el-tabs {
        height: 100%;
        .divclazz {
          width: 60%;
        }
        :deep(.el-tabs__content) {
          height: calc(100% - 40px);
          padding: 0;
          .el-tab-pane {
            height: 100%;
          }
          #pane-first {
            padding: 15px;
          }
        }
      }
    }
  }
}
</style>